package com.zly.framework.rbac.filter;

import com.alibaba.fastjson2.JSON;
import com.zly.framework.rbac.configuration.SysAuthConfiguration;
import com.zly.framework.rbac.model.vo.Result;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SysAuthConfiguration sysAuthConfiguration;
    @Resource
    private PathMatcher pathMatcher;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        for (String url : sysAuthConfiguration.getUrl().getCaptcha()) {
            boolean match = pathMatcher.match(url, request.getRequestURI());
            if (match) {
                String captcha = request.getParameter("captcha");
                String captchaId = request.getParameter("captchaId");
                if (!StringUtils.hasText(captchaId)) {
                    response.getWriter().write(JSON.toJSONString(Result.ERROR("验证码无效")));
                    return;
                }
                if (!StringUtils.hasText(captcha)) {
                    response.getWriter().write(JSON.toJSONString(Result.ERROR("请输入验证码")));
                    return;
                }
                String REDIS_KEY = sysAuthConfiguration.getRedis().getCaptcha() + captchaId;
                String code = stringRedisTemplate.opsForValue().get(REDIS_KEY);
                if (!StringUtils.hasText(code)) {
                    response.getWriter().write(JSON.toJSONString(Result.ERROR("验证码已过期")));
                    return;
                } else {
                    if (!code.equals(captcha)) {
                        response.getWriter().write(JSON.toJSONString(Result.ERROR("验证码错误")));
                        return;
                    }
                }
                break;
            }
        }
        filterChain.doFilter(request, response);
    }
}
